#include "ClientConfig.h"
#include "stdafx.h"

CClientConfig::CClientConfig()
{
	CreateAllDirectory();
}

BOOL  CClientConfig::BuildDirectory(CString  strPath)
{   
	CString   strSubPath;   
	CString   strInfo;   
	int   nCount   =   0;     
	int   nIndex   =   0;   

	do   
	{   
		nIndex   =   strPath.Find(_T("\\"),nIndex)   +   1;   
		nCount++;   
	}while(   (nIndex-1)   !=   -1);   

	nIndex   =   0;   
	while(   (nCount-1)   >=   0)   
	{   
		nIndex   =   strPath.Find(_T("\\"),nIndex)   +   1;   
		if(   (nIndex   -   1)   ==   -1)   
		{   
			strSubPath   =   strPath;   
		}   
		else   
			strSubPath   =   strPath.Left(nIndex);//strPath.substr(0,nIndex);   

		if(!PathFileExists((LPCTSTR)strSubPath)) 
		{   
			if(!::CreateDirectory((LPCTSTR)strSubPath,NULL))   
			{   
				strInfo   =   _T("Build   Directory");   
				strInfo   +=   strSubPath;   
				strInfo   +=   _T("   Fail!");   
				::MessageBox(NULL,_T(""),(LPCTSTR)strInfo,MB_OK);   
				return   FALSE;   
			}   
		}   
		nCount--;   
	};   

	return   TRUE;   
}   

void  CClientConfig::CreateAllDirectory()
{
	TCHAR szDefaultPath[MAX_PATH];
	TCHAR szBasePath[MAX_PATH];

	GetModuleFileName(NULL, szDefaultPath, MAX_PATH);
	PathRemoveFileSpec(szDefaultPath);
	if(szDefaultPath[_tcslen(szDefaultPath) - 1] != '\\')
		_tcscat(szDefaultPath, _T("\\"));

	if(SUCCEEDED(SHGetFolderPath(NULL,CSIDL_APPDATA|CSIDL_FLAG_CREATE,	NULL, 0, szBasePath))) 
	{
		if(szBasePath[_tcslen(szBasePath) - 1] != '\\')
			_tcscat(szBasePath, _T("\\"));
		
		m_ConfigPath = szBasePath;
		m_ConfigPath += _T("DocoMedia\\WinHomeServer\\");
		if (!BuildDirectory(m_ConfigPath.c_str()))
			m_ConfigPath = szDefaultPath;
	}
}
void	CClientConfig::SaveConfig()
{
	CString strFilePath = m_ConfigPath.c_str();
	strFilePath += SERVER_CONFIG_INI;

	BOOL bRet = FALSE;
	TCHAR szMode[MAX_PATH] = {0};
	_ltot_s(m_IPAddress, szMode, 10);
	bRet = ::WritePrivateProfileString(SERVERSETTINGS, KEY_IPADDRESS, szMode, (LPCTSTR)strFilePath);

	if (m_URLPath.length() >0)
		bRet = ::WritePrivateProfileString(SERVERSETTINGS, KEY_URL, m_URLPath.c_str(), (LPCTSTR)strFilePath);

	if (m_ConfigPath.length()>0)
		bRet = ::WritePrivateProfileString(SERVERSETTINGS, KEY_FILE, m_SharedFolder.c_str(), (LPCTSTR)strFilePath);
}
void	CClientConfig::LoadConfig()
{
	CString strFilePath = m_ConfigPath.c_str();
	strFilePath += SERVER_CONFIG_INI;

	m_IPAddress = ::GetPrivateProfileInt(SERVERSETTINGS, KEY_IPADDRESS, 0, (LPCTSTR)strFilePath);

	TCHAR szPath[MAX_PATH] = {0};
	DWORD dwRet = ::GetPrivateProfileString(SERVERSETTINGS, KEY_URL, szPath, szPath, MAX_PATH, (LPCTSTR)strFilePath);
	m_URLPath = szPath;

	dwRet = ::GetPrivateProfileString(SERVERSETTINGS, KEY_FILE, szPath, szPath, MAX_PATH, (LPCTSTR)strFilePath);
	m_SharedFolder = szPath;
}